import Vue from "vue"
import VueRouter from "vue-router"
import Login from "../components/Login.vue"
import Register from "../components/Register.vue"
import Home from "../components/Home.vue"
import User from "../components/User.vue"
import editUserInfo from "../components/editUserInfo.vue"
import Search from "../components/Search.vue"
import Play from "../components/Play.vue"

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    component: Login
  },
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: "/register",
    component: Register
  },
  {
    path: "/home",
    component: Home,
    meta: {
      keepAlive:true
    }
  },
  {
    path: "/user",
    component: User,
    meta: {
      isToken: true
    }
  },
  {
    path: "/edit",
    component: editUserInfo,
    meta: {
      isToken: true
    }
  },
  {
    path: "/search",
    component: Search
  },
  {
    path: "/play/:id",
    component: Play
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
//设置路由导航守卫
router.beforeEach((to, from, next) => {
  // to要去的页面 from从哪里来 next放行
  if (
    !localStorage.getItem("token") &&
    !localStorage.getItem("id") &&
    to.meta.isToken === true
  ) {
    router.push("/login");
  }
  next()
  return
})
export default router;
